<?php

namespace App\Http\Controllers;


use App\Models\PartCompany;
use App\Models\Project;
use App\Services\CommonService;
use App\Services\HomeService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class HomeController extends Controller
{
    public $homeService;

    public function __construct(HomeService $homeService)
    {
        parent::__construct();
        $this->homeService = $homeService;
    }

    /**
     * 获取经纬度
     *
     * @return JsonResponse
     * @author: lxk
     * @date: 2024/6/15 15:16
     */
    public function getMapLngAndLat() : JsonResponse
    {
        $data = $this->homeService->getLngAndLat();

        return $this->success($data);
    }

    /**
     * 获取当前公司下的项目
     *
     * @return JsonResponse
     * @author: lxk
     * @date: 2024-10-18 13:41
     */
    public function getProjects() : JsonResponse
    {
        $list = Project::query()->where('company_id', company_id())->select('id', 'title')->get()->toArray();

        return $this->success($list);
    }

    /**
     * 获取标段案卷
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024-10-18 17:54
     */
    public function getSectionArchives(Request $request) : JsonResponse
    {
        $projectId = $request->input('project_id');
        $list = PartCompany::query()
            ->where('project_id', $projectId)
            ->select('id', 'title', 'book_title_count', 'type')
            ->orderBy('type')
            ->get()
            ->toArray();
        $result = [];
        foreach ($list as $key=>&$val) {
            $type = str_replace('单位', '', PartCompany::TYPE[$val['type']]);
            $result[$key]['name']  = "[{$type}]-".$val['title'] ;
            $result[$key]['value'] = $val['book_title_count'];
        }

        return $this->success($result);
    }

    /**
     * 专业案卷
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024-10-18 17:54
     */
    public function getMajorCodeArchives(Request $request) : JsonResponse
    {
        $projectId        = $request->input('project_id');
        $redisKey         = 'HomeMajorCodeArchives:' . $projectId;
        if ($data = redis()->get($redisKey)) { //如果有缓存，用缓存
            return $this->success(json_decode($data, true));
        }
        $partCompanyIds   = PartCompany::query()->where('project_id', $projectId)->pluck('id')->toArray();
        $proClassBtCounts = HomeService::getProClassBtCounts($partCompanyIds);

        redis()->setex($redisKey, 3600 * 24 * 3, json_encode($proClassBtCounts));

        return $this->success($proClassBtCounts);
    }

    /**
     * 公司数据统计
     *
     * @return JsonResponse
     * @author: lxk
     * @date: 2024-11-11 16:56
     */
    public function companyData() : JsonResponse
    {
        $companyId    = company_id();
        $projectCount = Project::query()->where('company_id', $companyId)->count('id'); //建设项目数量

        $list = PartCompany::query()->where('company_id', $companyId)
            ->select('book_title_count', 'catalog_count', 'page_num_count', 'blueprint_count', 'blueprint_page_count')
            ->get()
            ->toArray();
        $bookTitleCount     = array_sum(array_column($list, 'book_title_count'));
        $catalogCount       = array_sum(array_column($list, 'catalog_count'));
        $pageNumCount       = array_sum(array_column($list, 'page_num_count'));
        $blueprintCount     = array_sum(array_column($list, 'blueprint_count'));
        $blueprintPageCount = array_sum(array_column($list, 'blueprint_page_count'));
        $docArchiveCount    = 0;
        if (Schema::hasTable("doc_archives_{$companyId}")) {
            $docArchiveCount = DB::table("doc_archives_{$companyId}")->whereNull('deleted_at')->where('company_id', $companyId)->count('id');
        }
        $photoArchiveCount  = PartCompany::query()->where('company_id', $companyId)->sum('photo_archive_count'); //照片案卷数
        $eArchiveCount      = $bookTitleCount + $docArchiveCount + $photoArchiveCount;

        $data = [
            'projectCount'       => $projectCount,
            'bookTitleCount'     => $bookTitleCount, //纸质案卷数
            'catalogCount'       => $catalogCount, //卷内数
            'pageNumCount'       => $pageNumCount, //页码数
            'blueprintCount'     => $blueprintCount, //蓝图件数
            'blueprintPageCount' => $blueprintPageCount, //蓝图张数
            'docArchiveCount'    => $docArchiveCount, //文书档案
            'photoArchiveCount'  => $photoArchiveCount, //照片档案
            'soundCount'         => 0, //音频档案
            'videoCount'         => 0, //视频档案
            'entityCount'        => 0, //实物档案
            'eArchiveCount'      => $eArchiveCount,
        ];

        return $this->success($data);
    }

    /**
     * 项目数据统计
     */
    public function getStatisticDetail(Request $request) : JsonResponse
    {
        $projectId = $request->input('project_id');
        $redisKey  = 'HomeStatistic:' . $projectId;
        if ($data = redis()->get($redisKey)) { //如果有缓存，用缓存，默认存放一周，但是如果手动更新数据，也会清除
            return $this->success(json_decode($data, true));
        }
        $list = PartCompany::query()
            ->where('project_id', $projectId)
            ->select('id', 'type', 'title', 'book_title_count', 'catalog_count', 'blueprint_count', 'blueprint_page_count', 'page_num_count', 'pdf_count', 'pdf_page_count', 'pdf_disk_count',
                'photo_archive_count', 'photo_catalog_count', 'photo_count', 'photo_disk_count')
            ->orderByDesc('type')
            ->get()
            ->toArray();

        $archivePercent = HomeService::getFiveStageTables($projectId);
        $stageBlueprint = HomeService::getBluePrintData($projectId);

        $bookTitleCount = array_sum(array_column($list, 'book_title_count')); //全部纸质案卷
        //$catalogCount = array_sum(array_column($list, 'catalog_count')); //全部纸质卷内
        $pageNumCount   = array_sum(array_column($list, 'page_num_count')); //全部纸质页数

        $blueBtCount = redis()->get('blue_bt_count:' . $projectId); //蓝图案卷
        //$blueCaCount = redis()->get('blue_ca_count:' . $projectId); //蓝图卷内
        $bluePnCount = redis()->get('blue_pn_count:' . $projectId); //蓝图页数

        $pdfCount     = array_sum(array_column($list, 'pdf_count'));
        $pdfPageCount = array_sum(array_column($list, 'pdf_page_count'));
        $pdfDiskCount = round(array_sum(array_column($list, 'pdf_disk_count')) / 1024, 1);

        $photoArchiveCount = array_sum(array_column($list, 'photo_archive_count'));
        $photoCatalogCount = array_sum(array_column($list, 'photo_catalog_count'));
        $photoCount        = array_sum(array_column($list, 'photo_count'));
        $photoDiskCount    = round(array_sum(array_column($list, 'photo_disk_count')) / 1024, 1); //把MB变为GB

        $data = [
            'archive_percent'     => $archivePercent,
            'blueprint'           => $stageBlueprint,
            'pre_refresh_time'    => isset($list[0]) ? CommonService::getFreshTime($projectId, $list[0]['id']) : '无需更新',
            'book_title_count'    => $bookTitleCount + $photoArchiveCount,
            //'catalog_count'       => $catalogCount,
            'page_num_count'      => $pageNumCount,
            'blue_bt_count'       => $blueBtCount, //总蓝图案卷
            //'blue_ca_count'       => $blueCaCount, //总蓝图卷内
            'blue_pn_count'       => $bluePnCount, //蓝图总张数
            'paper_bt_count'      => $bookTitleCount - $blueBtCount,
            //'paper_ca_count'      => $catalogCount - $blueCaCount,
            'paper_pn_count'      => $pageNumCount - $bluePnCount,
            'pdf_count'           => $pdfCount, //PDF件数
            'pdf_page_count'      => $pdfPageCount, //PDF页数
            'pdf_disk_count'      => $pdfDiskCount, //把MB变为GB
            'photo_archive_count' => $photoArchiveCount,
            'photo_catalog_count' => $photoCatalogCount,
            'photo_count'         => $photoCount,
            'photo_disk_count'    => $photoDiskCount,
        ];

        redis()->setex($redisKey, 3600 * 24 * 3, json_encode($data));

        return $this->success($data);
    }

    /**
     * 获取数据刷新时间
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024-11-04 11:57
     */
    public function getRefreshTime(Request $request) : JsonResponse
    {
        $projectId = $request->input('project_id');
        $data = [
            'refresh_time' => CommonService::getFreshTime($projectId),
        ];
        return $this->success($data);
    }



}
